package com.kt.thread.demo; /**
 * Created by tangwy on 2016/9/13.
 */

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 *
 */
public class ProducerAndConsumer {
    class Product{
        private static final int MAX_SIZE=10;
        private List<String> products=new ArrayList<String>(MAX_SIZE);
        Random random=new Random();
        public synchronized void set(){
            while (products.size()==MAX_SIZE){
                try {
                    System.out.println("生产达到上限.....");
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            String s= UUID.randomUUID().toString();
            products.add(s);
            this.notifyAll();
        }

        public synchronized String get(){
            while (products.size()==0){
                System.out.println("产品为0，等待生产.....");
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            int i=random.nextInt(products.size());
            String s=products.get(i);
            products.remove(i);
            this.notifyAll();
            return s;
        }
    }
}
